package org.gruposp2p.aularest.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jj
 */
public class DatabaseInstaller {

    private static final Logger logger =
            AulaLogger.getLogger(DatabaseInstaller.class.getName());
    public static String SYSTEM_BASEDIR =  System.getProperty("user.home")
            + File.separator + "aulaweb";
    public static final String DB_ZIP_FILE_NAME = "aulaweb_db.zip";
    public static final String DATABASE_DIR = SYSTEM_BASEDIR + File.separator +
            "db" + File.separator;
    public static final String DB_ZIP_FILE_SYSTEM_ABSOLUTE_PATH = DATABASE_DIR
            + DB_ZIP_FILE_NAME;
    //public static final String DB_ZIP_FILE_RESOURCE_PATH ="resources"
    //        + File.separator + DB_ZIP_FILE_NAME;
    public static final String DB_ZIP_FILE_RESOURCE_PATH = DB_ZIP_FILE_NAME;

    public static void install () {
        boolean mkdirAula = new File(SYSTEM_BASEDIR).mkdir();
        boolean mkdirDb = new File(DATABASE_DIR).mkdir();
        OutputStream dbos = null;
        try {
            dbos = new FileOutputStream(DB_ZIP_FILE_SYSTEM_ABSOLUTE_PATH);
        } catch (FileNotFoundException ex) {
            logger.log(Level.INFO, ex.toString(), ex);
        }
        InputStream dbis = DatabaseInstaller.class.getClassLoader()
            .getResourceAsStream(DB_ZIP_FILE_RESOURCE_PATH);
        try {
            FileUtils.copyInputstreamToFile(dbis, dbos);
            FileUtils.unzipFile(DB_ZIP_FILE_SYSTEM_ABSOLUTE_PATH,
                DATABASE_DIR);
            logger.log(Level.INFO, "DB_ZIP_FILE_SYSTEM_ABSOLUTE_PATH: " +
                DB_ZIP_FILE_SYSTEM_ABSOLUTE_PATH +
                " -DATABASE_DIR: " + DATABASE_DIR);
            if (dbis != null) dbis.close();
            if (dbos != null) dbos.close();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, ex.toString(), ex);
        }
    }
}
